//
//  RoomListViewController.m
//  wAudioShare
//
//  Created by Anson on 14-11-16.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "RoomListViewController.h"
#import "Utitlity.h"
#import "RoomItemModel.h"
#import "RoomEditViewController.h"

@interface RoomListViewController () <UIActionSheetDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) RoomItemModel *currentEditRoomData;
@property (strong, nonatomic) NSArray *icons;
@end

@implementation RoomListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    closeNextPage = YES;
    threadLoadData = NO;
    
    BottomView *bottomView = [self addBottomView];
    bottomView.btn_camera.hidden = YES;
    //[bottomView.btn_camera addTarget:self action:@selector(openCamera) forControlEvents:UIControlEventTouchUpInside];
    
    bottomView.btn_all_power.hidden = NO;
    [bottomView.btn_all_power addTarget:self action:@selector(showMenu:) forControlEvents:UIControlEventTouchUpInside];
    
    dataTableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - bottomView.frame.size.height);
    
    
    //dataTableView.frame = CGRectMake(0, 0, 320, self.view.frame.size.height - 60);
    self.title =@"房间";
    self.icons = [NSArray arrayWithObjects:@"scene_0",@"scene_1",@"scene_2",@"scene_3", nil];
    
    [self reqGetRoomList];
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationOfCurrentEditRoomData:) name:NOTIFICATION_ROOM_ITEM_CHANGE object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)notificationOfCurrentEditRoomData:(NSNotification *)obj {
    
    [dataTableView reloadData];
    
}

#pragma mark - Http Request
- (void)reqGetRoomList {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {

    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_list", ipUrl];
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            self.rows = [NSMutableArray arrayWithCapacity:10];
            NSArray *devList = retJsonData[@"data"];
            for (NSDictionary *item in devList) {
                
                RoomItemModel *data = [[RoomItemModel alloc] initWithJSON:item];
                [self.rows addObject:data];
            }
            NSLog(@"resultItem:%@",responseObject);
            [dataTableView reloadData];
        }
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    }
    
}

- (void)reqDelRoomItem:(RoomItemModel *)roomData {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    [activity startAnimating];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_destroy&room=%ld", ipUrl, roomData.roomId];
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            [self.rows removeObject:roomData];
            [dataTableView reloadData];
        }
        [dataTableView setEditing:NO];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
        [dataTableView setEditing:!dataTableView.editing animated:YES];
    }];
    }
}

- (void)reqNewRoomItem:(NSString *)roomName {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    ASIFormDataRequest *formDataRequest = [ASIFormDataRequest requestWithURL:nil];
    NSString *encodeRoomName = [formDataRequest encodeURL:roomName];
    
    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_create&name=%@", ipUrl, encodeRoomName];
    
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType
                       success:^(AFHTTPRequestOperation *operation, id responseObject) {
                           
                           if (!responseObject) return;
                           NSDictionary *retJsonData = responseObject;
                           if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                               
                               RoomItemModel *newRoomData = [[RoomItemModel alloc] initWithJSON:[retJsonData objectForKey:@"data"]];
                               [self.rows addObject:newRoomData];
                               [dataTableView reloadData];
                           }
                           
                           
                       }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                           NSLog(@"error:%@, httpStatusCode:%ld",error, operation.response.statusCode);
                       }];
    }
}

#pragma mark -
- (void)showMenu:(UIButton *)sender {
    
    UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"添加房间" otherButtonTitles:@"删除房间", nil];
    [menu showFromRect:sender.frame inView:self.view animated:YES];
}

#pragma mark - UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
        {
            UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:@"新增房间" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            prompt.alertViewStyle = UIAlertViewStylePlainTextInput;
            [prompt textFieldAtIndex:0].placeholder = @"名称";
            [prompt show];
            break;
        }
        case 1:
            
            break;
            
        default:
            break;
    }
    
}

#pragma mark - UIAlertView
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 1) {
        
        [self reqNewRoomItem:[alertView textFieldAtIndex:0].text];
    }
}

#pragma mark - UITableView Delegate
-(CGFloat)rowHeight
{
    return 60;
}

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
    static NSString *RoomCellIdentifier = @"RoomCellIdentifier";
    UITableViewCell *cell = [dataTableView dequeueReusableCellWithIdentifier:RoomCellIdentifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RoomCellIdentifier];
        
        UIImage *img1  = [UIImage imageNamed:@"bg_cell"];
        UIImage *img2  = [UIImage imageNamed:@"bg_cell_sel"];
        
        UIImageView *cellbg1 = [[UIImageView alloc]initWithImage:img1];
        UIImageView *cellbg2 = [[UIImageView alloc]initWithImage:img2];
        
        cell.backgroundView = cellbg1;
        cell.selectedBackgroundView = cellbg2;
    }
    
    
    RoomItemModel *rowData = self.rows[row];
    cell.textLabel.text = rowData.roomName;
    
    UIImage *img = [UIImage imageNamed:[self.icons objectAtIndex:row%[self.icons count]]];
    
    cell.imageView.image = [self scaleImage:img toSize:CGSizeMake(img.size.width/3, img.size.height/3)];
    return cell;
}

-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RoomEditViewController *vc = [[RoomEditViewController alloc] initWithNibName:nil bundle:nil];
    [vc setEditRoomData:self.rows[indexPath.row]];
    [vc setRoomList:self.rows];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RoomItemModel *rowData = self.rows[indexPath.row];
    [self reqDelRoomItem:rowData];
}


-(UIImage*)scaleImage:(UIImage *)img toSize:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}


@end
